package com.supermap.business.cloud.api;

import com.alibaba.dubbo.config.annotation.Reference;
import com.supermap.dataservice.redis.JedisComponent;
import com.supermap.dataservice.util.AquaMd5;
import com.supermap.dataservice.util.JSONUtil;
import com.supermap.dubbo.api.cloud.api.ApiUserService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author aqua
 * @desc
 * @date 2019年06月04 16:31
 * @email 1301584033@qq.com
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    JedisComponent jedisComponent;
    @Reference(timeout = 100000)
    ApiUserService apiUserService;
    //这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //每一个项目对于登陆的实现逻辑都有所区别，我这里使用最简单的Session提取User来验证登陆。
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        String token=request.getParameter("token");
        String appKey=null;
        if(Strings.isNotBlank(token)){
            if(jedisComponent.exists(token)){
                appKey=jedisComponent.get(token);
            }
        }
        String redisToken=null;
        if(Strings.isNotBlank(appKey)){
            if(jedisComponent.exists(appKey)){
                redisToken=jedisComponent.get(appKey);
            }
        }
        JSONUtil jsonUtil= new JSONUtil();
        String url=request.getRequestURI();
        if(url.indexOf("/ChinaAPP/api/")!=-1){
            url=url.replace("/ChinaAPP/api","");
        }else if(url.indexOf("//")!=-1){
            response.getWriter().write(jsonUtil.setCode(100).setMsg("请求地址非法！").getJsonStr());
            return false;
        }else {
            return true;
        }
        if(!Strings.isNotBlank(appKey)){
            response.getWriter().write(jsonUtil.setCode(100).setMsg("token解析错误！").getJsonStr());
            return false;
        }
        //权限校验
        if(Strings.isNotBlank(token)){
            if(Strings.isNotBlank(redisToken)){
                if(token.equals(redisToken)){
                    //判断时间是否有效
                    if(apiUserService.apiTimeIsNotTake(url,appKey)>0){
                        RequestDispatcher requestDispatcher=request.getRequestDispatcher(url);
                        requestDispatcher.forward(request,response);
                    }else{
                        response.getWriter().write(jsonUtil.setCode(100).setMsg("接口有效时间已过期！").getJsonStr());
                        return false;
                    }
                }else{
                    jsonUtil.setMsg("验证失败,令牌错误!").setCode(100);
                    response.getWriter().write(jsonUtil.getJsonStr());
                    return  false;
                }
            }else{
                jsonUtil.setMsg("token已失效,请重新验证!").setCode(100);
                response.getWriter().write(jsonUtil.getJsonStr());
                return  false;
            }
        }else {
            jsonUtil.setMsg("token不能为空！").setCode(100);
            response.getWriter().write(jsonUtil.getJsonStr());
            return  false;
        }
         response.getWriter().write(jsonUtil.setCode(100).setMsg("验证不通过，请联系管理员").getJsonStr());
         return false;

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
